<template>
  <div class="comment">
    <!-- 表单区域 -->
    <van-field
      class="content"
      v-model="content"
      rows="2"
      autosize
      label="发表评论"
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <!-- 提交按钮 -->
    <van-button
      class="add"
      type="primary"
      block
      @click="addComments"
    >提交评论</van-button>
    <!-- 列表渲染 -->
    <van-card
      :desc="comment.content"
      v-for="comment in comments"
      :key="comment.id"
    >
      <template #title>
        <van-rate
          class="my-rate"
          v-model="comment.rate"
        />
      </template>

      <template #price>
        {{comment.add_time}}
      </template>
      <template #thumb>
        <div>
          <van-icon name="https://b.yzcdn.cn/vant/icon-demo-1126.png" />
          <span>匿名用户</span>
        </div>
      </template>
    </van-card>

    <!-- 提交按钮 -->
    <van-button
      type="primary"
      block
      @click="getMore"
    >{{moreText}}</van-button>
  </div>
</template>
<script>
export default {
  props: ["id"],
  data: () => ({
    content: "",
    pageNo: 0,
    pageSize: 200,
    comments: [],
    hasMore: false
  }),
  created() {
    this.getComments()
  },
  methods: {
    async getComments() {
      if (this.hasMore !== false) return
      ++this.pageNo
      const res = await this.$http.getComments({
        id: this.id,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      })
      // 把上一页和下一页的数据进行拼接
      this.comments = this.comments.concat(res.data.message)
      // 判断数据的临界点
      this.hasMore = this.pageNo * this.pageSize > res.data.count
      console.log(this.hasMore)
    },
    async addComments() {
      await this.$http.addComments({
        id: this.id,
        content: this.content
      })

      this.comments.unshift({
        id: new Date().getTime(),
        content: this.content,
        rate: 5,
        add_time: new Date().getTime()
      })
    },
    getMore() {
      this.getComments()
    }
  },
  computed: {
    moreText() {
      return this.hasMore ? "被掏空了" : "加载更多"
    }
  }
}
</script>
<style lang="scss">
.comment {
  margin-top: 20px;
  .van-cell__title {
    span {
      font-size: 16px;
      font-weight: 600;
    }
  }
  .content {
    border: 1px solid #ddd;
  }
  .add {
    margin-top: 10px;
  }

  .van-icon {
    font-size: 45px;
    display: block;
  }

  .my-rate {
    .van-icon {
      font-size: 12px;
    }
  }
}
</style>
